package com.xingdata.jjxc.udp;

import android.util.Log;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.ArrayList;
import java.util.List;

public class UdpServerThread {
  String Tag = "UdpThread";
  private int mPort = 18944;
  private DatagramSocket socket;
  ServerThread serverThread;

  public interface DataReceiveListener{
     void OnDataReceived(String data);
  }

  List<DataReceiveListener> dataReceiveListeners = new ArrayList<>();

  public UdpServerThread(int port) throws IOException {
    socket = new DatagramSocket(port); //初始化服务
    System.out.println(" UdpServerThread 启动!");
    mPort = port;
    serverThread = new ServerThread();
    serverThread.startThread();
    serverThread.start();
  }

  public void addDataRecieveListener(DataReceiveListener listener){
    synchronized (dataReceiveListeners){
      dataReceiveListeners.add(listener);
    }
  }

  public void removeDataReceiveListener(DataReceiveListener listener){
    synchronized (dataReceiveListeners){
      dataReceiveListeners.remove(listener);
    }
  }

  private void notifyDataReceived(String data){
    synchronized (dataReceiveListeners){
      for(DataReceiveListener l: dataReceiveListeners){
        l.OnDataReceived(data);
      }
    }
  }

  public String echo(String msg) {
    return "echo:" + msg;
  }

  public void service() {
  }

  public static void main(String args[])throws IOException {
    // new UdpServerThread().service();
  }

  class ServerThread extends Thread {
    public ServerThread(){
    }

    public void startThread(){
      isRunning = true;
    }

    public void stopThread(){
      isRunning = false;
      interrupt();
    }

    boolean isRunning = false;

    @Override
    public void run() {
      DatagramPacket packet = new DatagramPacket(new byte[1024],1024);
        Log.w(Tag,"-----------------> Waiting for udp msg");
        try {
          while (isRunning && !isInterrupted()) {
            socket.receive(packet);  //接收数据包
            String msg = new String(packet.getData(),0,packet.getLength());
            Log.e(Tag,"=UDP server Thread >接收到:"+packet.getAddress()
                    + ":" +packet.getPort()
                    +"> "+ msg);
            //TODO handle msg
            notifyDataReceived(msg);
          }
        }catch (IOException e) {
          e.printStackTrace();
        }finally {
            isRunning =false;
            if(socket!=null){
                socket.close();
            }
            interrupt();
        }
      }
    }
}
